package models

import (
	"time"
)

type ArticleLabel struct {
	ID        int       `gorm:"primary_key" json:"id"`
	Name      string    `json:"name"`
	Sort      string    `json:"sort"`
	IsEnabled int       `json:"is_enabled"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}
type ArticleLabels struct {
	ID        int       `gorm:"primary_key" json:"id"`
	Name      string    `json:"name"`
	Sort      string    `json:"sort"`
	IsEnabled int       `json:"is_enabled"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Num       int       `json:"num"`
}

type GetArticleLabelSelectResult struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type ArticleNum struct {
	Num int `json:"num"`
}

func GetArticleLabels() ([]*ArticleLabels, error) {
	var data []*ArticleLabels
	err := DB.Table("article_label").Order("sort asc").Find(&data).Error
	if err != nil {
		return nil, err
	}

	for i := 0; i < len(data); i++ {
		var num ArticleNum

		DB.Table("articles").Select("count(*) as num").Where("label_id=?", data[i].ID).First(&num)
		data[i].Num = num.Num
	}
	return data, err
}
func GetArticleLabelSelect() ([]*GetArticleLabelSelectResult, error) {
	var data []*GetArticleLabelSelectResult
	err := DB.Table("article_label").Select("id, name").Where("is_enabled=?", 0).Order("sort asc").Find(&data).Error
	if err != nil {
		return nil, err
	}
	return data, nil
}

func GetArticleLabelById(id int) (*ArticleLabel, error) {
	var data ArticleLabel
	err := DB.Table("article_label").Where("id=?", id).First(&data).Error
	if err != nil {
		return nil, err
	}
	return &data, nil
}

func (a *ArticleLabel) AddArticleLabel() error {
	err := DB.Table("article_label").Create(a).Error
	if err != nil {
		return err
	}
	return nil
}

func UpdateArticleLabel(data map[string]interface{}) error {
	err := DB.Table("article_label").Where("id=?", data["id"]).Updates(data).Error
	if err != nil {
		return err
	}
	return nil
}

func DeletedArticleLabel(id int) error {
	err := DB.Delete(ArticleLabel{}, "id=?", id).Error
	if err != nil {
		return err
	}
	return nil
}
